package com.devops.admin.event.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.aliyun.dingtalkim_1_0.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.devops.admin.config.DingTalkConfig;
import com.devops.admin.event.ProjectVersionPhaseChangeEvent;
import com.devops.admin.mapper.DOSProjectMapper;
import com.devops.admin.model.*;
import com.devops.admin.po.DOSProjectPo;
import com.devops.admin.po.DOSProjectVersionPhaseCardDataPo;
import com.devops.admin.po.DOSProjectVersionPhasePrivateCardDataPo;
import com.devops.admin.service.*;
import com.devops.admin.util.Assert;
import com.devops.admin.util.WebhookUtil;
import com.devops.constant.DevOpsConstant;
import com.devops.constant.InteractiveCardTypeEnum;
import com.devops.constant.ProjectVersionPhaseEnum;
import com.devops.shiro.service.DOSBaseUserService;
import com.devops.shiro.vm.BaseUserVM;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author jxt
 * @Notes
 * @date 2023/3/16 9:56
 */
@Slf4j
@EnableAsync
@Service
public class ProjectVersionPhaseChangeEventListener {

    @Resource
    private DingtalkInteractiveCardService dingtalkInteractiveCardService;
    @Resource
    private DingtalkInteractiveCardReceiverService dingtalkInteractiveCardReceiverService;
    @Resource
    private DOSProjectMapper dosProjectMapper;
    @Resource
    private DOSProjectVersionOperateLogService dosProjectVersionOperateLogService;
    @Resource
    private DOSBaseUserService dosBaseUserService;
    @Resource
    private DingTalkService dingTalkService;
    @Resource
    private com.aliyun.dingtalkim_1_0.Client dingTalkIMClient;
    @Resource
    private DingTalkConfig dingTalkConfig;
    @Value("#{'${admin.user.ids}'.split(',')}")
    private List<String> adminUsers = new ArrayList<>();
    @Value("${release.notify.method:1}")
    private Integer notifyMethod;

    private static final Integer WEBHOOK_METHOD = 1;
    private static final Integer ACTION_CARD_METHOD = 2;
    @Async
    @EventListener({ProjectVersionPhaseChangeEvent.class})
    public void onApplicationEvent(ProjectVersionPhaseChangeEvent event) {
        DOSProjectVersion dosProjectVersion = event.getDosProjectVersion();
        String currentUserName = event.getCurrentUser() == null ? "" : event.getCurrentUser().getRealName();
        ProjectVersionPhaseEnum phaseEnum = (ProjectVersionPhaseEnum)event.getSource();
        if ((notifyMethod & WEBHOOK_METHOD) > 0) {
            pushByWebhook(dosProjectVersion, phaseEnum);
        }
        if ((notifyMethod & ACTION_CARD_METHOD) > 0) {
            pushByActionCard(dosProjectVersion, currentUserName, phaseEnum);
        }
    }

    private void pushByActionCard(DOSProjectVersion dosProjectVersion, String currentUserName,
                           ProjectVersionPhaseEnum phaseEnum) {
        List<DingtalkInteractiveCard> interactiveCards = dingtalkInteractiveCardService.lambdaQuery()
                .eq(DingtalkInteractiveCard::getType, InteractiveCardTypeEnum.RELEASE_APPLICATION.getType())
                .eq(DingtalkInteractiveCard::getStatus,DevOpsConstant.Status.ACTIVE)
                .list();
        if (CollUtil.isEmpty(interactiveCards)) {
            return;
        }
        DingtalkInteractiveCard interactiveCard = interactiveCards.get(0);
        String outTrackId = StrUtil.format("{}_{}", interactiveCard.getCallbackRouteKey(), dosProjectVersion.getId());
        dosProjectVersion.setOutTrackId(outTrackId);
        DOSProjectPo projectPo = dosProjectMapper.getProjectInfo(dosProjectVersion.getProjectId());
        List<DOSProjectVersionOperateLog> logList = dosProjectVersionOperateLogService.lambdaQuery()
                .eq(DOSProjectVersionOperateLog::getVersionId, dosProjectVersion.getId())
                .eq(DOSProjectVersionOperateLog::getLogType, DevOpsConstant.ProjectVersionOperateLogType.ACTION_TYPE)
                .list();
        if (Objects.requireNonNull(phaseEnum) == ProjectVersionPhaseEnum.APPLY) {
            createCard(dosProjectVersion, projectPo, interactiveCard, currentUserName);
        } else {
            List<DOSProjectVersionOperateLog> logMap = logList.stream()
                    .sorted(Comparator.comparing(DOSProjectVersionOperateLog::getUpdateTime).reversed())
                    .collect(Collectors.groupingBy(DOSProjectVersionOperateLog::getActionType))
                    .get(DevOpsConstant.ProjectVersionOperateActionType.CREATE);
            String submitter = logMap.get(0).getOperateUserName();
            updateCard(dosProjectVersion, projectPo, phaseEnum, submitter, currentUserName);
        }
    }

    /**
     * createCard
     * @param dosProjectVersion 发版
     * @param projectPo 项目
     * @param interactiveCard 互动卡片配置
     * @param submitter 发版申请人
     * @return void
     * @author jxt
     * @date 2023/3/20 15:24
     */
    private void createCard(DOSProjectVersion dosProjectVersion, DOSProjectPo projectPo,
                            DingtalkInteractiveCard interactiveCard, String submitter) {
        SendInteractiveCardHeaders sendInteractiveCardHeaders = buildSendCardHeaders();
        SendInteractiveCardRequest.SendInteractiveCardRequestCardData cardData = buildSendCardData(dosProjectVersion, projectPo, submitter);
        Map<String, PrivateDataValue> privateData = buildPrivateData();
        SendInteractiveCardRequest sendInteractiveCardRequest = buildSendCardRequest(dosProjectVersion, interactiveCard, cardData, privateData);
        try {
            dingTalkIMClient.sendInteractiveCardWithOptions(sendInteractiveCardRequest, sendInteractiveCardHeaders, new RuntimeOptions());
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                log.error("dingtalk send card message error {}", err.message);
            }
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                log.error("dingtalk send card message error {}", err.message);
            }
        }
    }

    /**
     * buildSendCardHeaders
     * @return com.aliyun.dingtalkim_1_0.models.SendInteractiveCardHeaders
     * @author jxt
     * @date 2023/3/20 15:25
     */
    @NotNull
    private SendInteractiveCardHeaders buildSendCardHeaders() {
        SendInteractiveCardHeaders sendInteractiveCardHeaders = new SendInteractiveCardHeaders();
        String accessToken = dingTalkService.getAccessToken();
        Assert.isTrue(StrUtil.isNotBlank(accessToken), "获取钉钉accessToken失败");
        sendInteractiveCardHeaders.xAcsDingtalkAccessToken = accessToken;
        return sendInteractiveCardHeaders;
    }

    /**
     * buildSendCardData
     * @param dosProjectVersion 发版
     * @param projectPo 项目
     * @param submitter 申请人
     * @return com.aliyun.dingtalkim_1_0.models.SendInteractiveCardRequest.SendInteractiveCardRequestCardData
     * @author jxt
     * @date 2023/3/20 15:25
     */
    @NotNull
    private SendInteractiveCardRequest.SendInteractiveCardRequestCardData buildSendCardData(DOSProjectVersion dosProjectVersion, DOSProjectPo projectPo, String submitter) {
        SendInteractiveCardRequest.SendInteractiveCardRequestCardData cardData = new SendInteractiveCardRequest.SendInteractiveCardRequestCardData();
        DOSProjectVersionPhaseCardDataPo cardDataPo = DOSProjectVersionPhaseCardDataPo.builder()
                .submitter(submitter)
                .phaseLabel(ProjectVersionPhaseEnum.APPLY.getPhaseLabel())
                .labelColor(ProjectVersionPhaseEnum.APPLY.getLabelColor())
                .projectGroup(projectPo.getGroupName())
                .projectName(projectPo.getProjectName())
                .versionCode(dosProjectVersion.getVersionCode())
                .updateLog(dosProjectVersion.getUpdateLog())
                .createTime(DateUtil.formatLocalDateTime(dosProjectVersion.getCreateTime()))
                .updateTime(DateUtil.formatLocalDateTime(dosProjectVersion.getCreateTime()))
                .versionId(dosProjectVersion.getId().toString())
                .sys_lastMessageI18n(lastMessage())
                .build();
        Map<String, Object> map = BeanUtil.beanToMap(cardDataPo);
        Map<String, String> cardParamMap = new HashMap<>();
        map.forEach((key, value) -> cardParamMap.put(key, value != null ? value.toString() : null));
        cardData.setCardParamMap(cardParamMap);
        return cardData;
    }

    @NotNull
    private String lastMessage() {
        JSONObject lastMessage = new JSONObject();
        lastMessage.set("zh_CN", InteractiveCardTypeEnum.RELEASE_APPLICATION.getMessageCN());
        lastMessage.set("en_US", InteractiveCardTypeEnum.RELEASE_APPLICATION.getMessageUS());
        return lastMessage.toString();
    }

    /**
     * buildPrivateData
     * @return java.util.Map<java.lang.String,com.aliyun.dingtalkim_1_0.models.PrivateDataValue>
     * @author jxt
     * @date 2023/3/20 15:23
     */
    @NotNull
    private Map<String, PrivateDataValue> buildPrivateData() {
        Map<String, PrivateDataValue> privateData = new HashMap<>();
        List<BaseUser> baseUsers = dosBaseUserService.listByIds(adminUsers);
        baseUsers.forEach(adminUser -> {
            DOSProjectVersionPhasePrivateCardDataPo privateCardDataPo = DOSProjectVersionPhasePrivateCardDataPo.builder()
                    .userId(adminUser.getId())
                    .userName(adminUser.getRealName())
                    .isAdmin("true")
                    .build();
            Map<String, Object> privateMap = BeanUtil.beanToMap(privateCardDataPo);
            Map<String, String> privateDataMap = new HashMap<>();
            privateMap.forEach((key, value) -> privateDataMap.put(key, value.toString()));
            PrivateDataValue privateDataValue = new PrivateDataValue();
            privateDataValue.setCardParamMap(privateDataMap);
            if (StrUtil.isNotBlank(adminUser.getDingtalkUserId())) {
                privateData.put(adminUser.getDingtalkUserId(), privateDataValue);
            }
        });
        return privateData;
    }

    /**
     * buildSendCardRequest
     * @param dosProjectVersion 发版
     * @param interactiveCard 互动卡片配置
     * @param cardData 卡片数据
     * @param privateData 私有数据
     * @return com.aliyun.dingtalkim_1_0.models.SendInteractiveCardRequest
     * @author jxt
     * @date 2023/3/20 15:25
     */
    private SendInteractiveCardRequest buildSendCardRequest(DOSProjectVersion dosProjectVersion,
                                                            DingtalkInteractiveCard interactiveCard,
                                                            SendInteractiveCardRequest.SendInteractiveCardRequestCardData cardData, Map<String, PrivateDataValue> privateData) {
        SendInteractiveCardRequest sendInteractiveCardRequest = new SendInteractiveCardRequest()
                .setOutTrackId(dosProjectVersion.getOutTrackId())
                .setConversationType(interactiveCard.getConversationType())
                .setCardData(cardData)
                .setPrivateData(privateData)
                .setCallbackRouteKey(interactiveCard.getCallbackRouteKey())
                .setCardTemplateId(interactiveCard.getCardTemplateId())
                .setRobotCode(dingTalkConfig.getRobotCode());
        List<DingtalkInteractiveCardReceiver> receivers = dingtalkInteractiveCardReceiverService.lambdaQuery()
                .eq(DingtalkInteractiveCardReceiver::getInteractiveCardId, interactiveCard.getId())
                .list();
        if (CollUtil.isEmpty(receivers)) {
            log.error("dingtalk send card message error {}", "none receivers");
        }
        if (DevOpsConstant.ConversationType.USER.equals(interactiveCard.getConversationType())) {
            sendInteractiveCardRequest.setReceiverUserIdList(receivers.stream().map(receiver -> dosBaseUserService.getById(receiver.getReceiverId()).getDingtalkUserId()).collect(Collectors.toList()));
        } else if (DevOpsConstant.ConversationType.GROUP.equals(interactiveCard.getConversationType())) {
            sendInteractiveCardRequest.setOpenConversationId(receivers.get(0).getReceiverId());
        }
        return sendInteractiveCardRequest;
    }

    /**
     * updateCard
     * @param dosProjectVersion 发版
     * @param projectPo 项目
     * @param phaseEnum 发版阶段枚举
     * @param submitter 发版申请人
     * @param currentUserName 当前操作人
     * @return void
     * @author jxt
     * @date 2023/3/20 15:22
     */
    private void updateCard(DOSProjectVersion dosProjectVersion, DOSProjectPo projectPo, ProjectVersionPhaseEnum phaseEnum,
                            String submitter, String currentUserName) {
        UpdateInteractiveCardHeaders updateInteractiveCardHeaders = buildUpdateCardHeaders();
        UpdateInteractiveCardRequest.UpdateInteractiveCardRequestCardData cardData = buildUpdateCardData(dosProjectVersion, projectPo, phaseEnum, submitter, currentUserName);
        Map<String, PrivateDataValue> privateData = buildPrivateData();
        UpdateInteractiveCardRequest updateInteractiveCardRequest = new UpdateInteractiveCardRequest()
                .setOutTrackId(dosProjectVersion.getOutTrackId())
                .setCardData(cardData)
                .setPrivateData(privateData);

        try {
            dingTalkIMClient.updateInteractiveCardWithOptions(updateInteractiveCardRequest, updateInteractiveCardHeaders, new RuntimeOptions());
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                log.error("dingtalk update card message error {}", err.message);
            }
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                log.error("dingtalk update card message error {}", err.message);
            }
        }
    }

    /**
     * buildUpdateCardHeaders
     * @return com.aliyun.dingtalkim_1_0.models.UpdateInteractiveCardHeaders
     * @author jxt
     * @date 2023/3/20 15:23
     */
    @NotNull
    private UpdateInteractiveCardHeaders buildUpdateCardHeaders() {
        UpdateInteractiveCardHeaders updateInteractiveCardHeaders = new UpdateInteractiveCardHeaders();
        String accessToken = dingTalkService.getAccessToken();
        Assert.isTrue(StrUtil.isNotBlank(accessToken), "获取钉钉accessToken失败");
        updateInteractiveCardHeaders.xAcsDingtalkAccessToken = accessToken;
        return updateInteractiveCardHeaders;
    }

    /**
     * buildUpdateCardData
     * @param dosProjectVersion 发版
     * @param projectPo 项目
     * @param phaseEnum 发版阶段枚举
     * @param submitter 发版申请人
     * @param currentUserName 当前操作人
     * @return com.aliyun.dingtalkim_1_0.models.UpdateInteractiveCardRequest.UpdateInteractiveCardRequestCardData
     * @author jxt
     * @date 2023/3/20 15:24
     */
    @NotNull
    private UpdateInteractiveCardRequest.UpdateInteractiveCardRequestCardData buildUpdateCardData(DOSProjectVersion dosProjectVersion, DOSProjectPo projectPo,
                                                                                                         ProjectVersionPhaseEnum phaseEnum, String submitter, String currentUserName) {
        UpdateInteractiveCardRequest.UpdateInteractiveCardRequestCardData cardData = new UpdateInteractiveCardRequest.UpdateInteractiveCardRequestCardData();
        DOSProjectVersionPhaseCardDataPo cardDataPo = DOSProjectVersionPhaseCardDataPo.builder()
                .submitter(submitter)
                .operatorName(currentUserName)
                .phaseLabel(phaseEnum.getPhaseLabel())
                .labelColor(phaseEnum.getLabelColor())
                .projectGroup(projectPo.getGroupName())
                .projectName(projectPo.getProjectName())
                .versionCode(dosProjectVersion.getVersionCode())
                .updateLog(dosProjectVersion.getUpdateLog())
                .createTime(DateUtil.formatLocalDateTime(dosProjectVersion.getCreateTime()))
                .updateTime(DateUtil.formatLocalDateTime(LocalDateTime.now()))
                .versionId(dosProjectVersion.getId().toString())
                .sys_lastMessageI18n(lastMessage())
                .build();
        Map<String, Object> map = BeanUtil.beanToMap(cardDataPo);
        Map<String, String> cardParamMap = new HashMap<>();
        map.forEach((key, value) -> cardParamMap.put(key, value != null ? value.toString() : null));
        cardData.setCardParamMap(cardParamMap);
        return cardData;
    }

    @Resource
    private DOSProjectWebhookService dosProjectWebhookService;
    @Value("${project.env}")
    String projectEnv;
    /**
     * @param dosProjectVersion
     * @param msgType           1-申请发版 2-审核通过 3-发版超时(xxl-job调度) 4-web页面发布完成
     */
    private void pushByWebhook(DOSProjectVersion dosProjectVersion, ProjectVersionPhaseEnum msgType) {
        LambdaQueryWrapper<DOSProjectWebhook> queryWrapper = Wrappers.<DOSProjectWebhook>lambdaQuery()
                .eq(DOSProjectWebhook::getType, 1)
                .eq(DOSProjectWebhook::getSubType, 2)
                .eq(DOSProjectWebhook::getStatus,1);
        List<DOSProjectWebhook> webhooks = dosProjectWebhookService.list(queryWrapper);
        if (webhooks.size() > 0) {
            DOSProjectPo projectPo = dosProjectMapper.getProjectInfo(dosProjectVersion.getProjectId());
            List<DOSProjectVersionOperateLog> logList = dosProjectVersionOperateLogService.list(Wrappers.<DOSProjectVersionOperateLog>lambdaQuery()
                    .eq(DOSProjectVersionOperateLog::getVersionId, dosProjectVersion.getId())
                    .eq(DOSProjectVersionOperateLog::getLogType, DevOpsConstant.ProjectVersionOperateLogType.ACTION_TYPE));
            Map<Integer, List<DOSProjectVersionOperateLog>> logMap = logList.stream()
                    .sorted(Comparator.comparing(DOSProjectVersionOperateLog::getUpdateTime).reversed())
                    .collect(Collectors.groupingBy(DOSProjectVersionOperateLog::getActionType));
            JSONObject msgJson = new JSONObject();
            if (ProjectVersionPhaseEnum.APPLY == msgType) {
                /**
                 * 申请发版 目前只有两种场景
                 * 1-创建一个包含uat pro两个环境的版本，这时候谁点击测试完成 谁就是申请发版的的申请人
                 * 2-创建一个仅包含pro环境的版本，这时候谁点击创建版本 谁就是申请发版的申请人
                 * 综上所述 操作人就是申请人
                 */
                BaseUserVM user = (BaseUserVM) SecurityUtils.getSubject().getPrincipal();
                String operateUserName = user.getRealName();

                //申请发版 actionCard格式
                String title = "申请发版";
                String content = "**项目组**:" + projectPo.getGroupName() + "\n\n" +
                        "**项目**:" + projectPo.getProjectName() + "\n\n" +
                        "**版本**:" + dosProjectVersion.getVersionCode() + "\n\n" +
                        "**更新日志**:" + dosProjectVersion.getUpdateLog() + "\n\n" +
                        "**申请人**:" + operateUserName + "\n\n" +
                        "**Message**:" + title;
                JSONObject actionCardJson = new JSONObject();
                actionCardJson.set("title", title);
                actionCardJson.set("text", content);
                actionCardJson.set("btnOrientation", "0");
                actionCardJson.set("singleTitle", "同意");
                actionCardJson.set("singleURL", projectEnv + "/devops-middle.html?type=1&versionId=" + dosProjectVersion.getId());

                msgJson.set("msgtype", "actionCard");
                msgJson.set("actionCard", actionCardJson);
            } else if (ProjectVersionPhaseEnum.APPROVED == msgType) {
                //审核通过 markdown格式
                String title = "审核通过";
                String operateUserName = "";
                List<DOSProjectVersionOperateLog> acceptLogList = logMap.get(DevOpsConstant.ProjectVersionOperateActionType.REVIEW_ACCEPT);
                List<DOSProjectVersionOperateLog> webhookAcceptLogList = logMap.get(DevOpsConstant.ProjectVersionOperateActionType.WEBHOOK_REVIEW_ACCEPT);
                List<DOSProjectVersionOperateLog> dealLogList = new ArrayList<>();

                if (CollectionUtil.isNotEmpty(acceptLogList)) {
                    dealLogList.addAll(acceptLogList);
                }
                if (CollectionUtil.isNotEmpty(webhookAcceptLogList)) {
                    dealLogList.addAll(webhookAcceptLogList);
                }
                if (CollectionUtil.isNotEmpty(dealLogList)) {
                    DOSProjectVersionOperateLog firstAcceptLog = dealLogList.get(0);
                    if (firstAcceptLog.getId() != null && StrUtil.isNotBlank(firstAcceptLog.getOperateUserName())) {
                        operateUserName = firstAcceptLog.getOperateUserName();
                    }
                }
                String content = "**项目组**:" + projectPo.getGroupName() + "\n\n" +
                        "**项目**:" + projectPo.getProjectName() + "\n\n" +
                        "**版本**:" + dosProjectVersion.getVersionCode() + "\n\n" +
                        "**更新日志**:" + dosProjectVersion.getUpdateLog() + "\n\n" +
                        "**审核人**:" + operateUserName + "\n\n" +
                        "**Message**:" + title;

                JSONObject mdJson = new JSONObject();
                mdJson.set("title", title);
                mdJson.set("text", content);
                msgJson.set("msgtype", "markdown");
                msgJson.set("markdown", mdJson);
            } else if (ProjectVersionPhaseEnum.TIMEOUT == msgType) {
                //发版超时 actionCard格式
                String operateUserName = "";
                DOSProjectVersionOperateLog applicationLog = dosProjectVersionOperateLogService.getOne(Wrappers.<DOSProjectVersionOperateLog>lambdaQuery()
                        .eq(DOSProjectVersionOperateLog::getPhaseStatusType, DevOpsConstant.ProjectVersionPhaseStatusType.QA_REVIEW_WAIT)
                        .eq(DOSProjectVersionOperateLog::getLogType, DevOpsConstant.ProjectVersionOperateLogType.STATUS_TYPE)
                        .eq(DOSProjectVersionOperateLog::getVersionId, dosProjectVersion.getId()));
                if (applicationLog != null && applicationLog.getId() > 0){
                    operateUserName = applicationLog.getOperateUserName();
                }
                String title = "发版超时";
                String content = "**项目组**:" + projectPo.getGroupName() + "\n\n" +
                        "**项目**:" + projectPo.getProjectName() + "\n\n" +
                        "**版本**:" + dosProjectVersion.getVersionCode() + "\n\n" +
                        "**更新日志**:" + dosProjectVersion.getUpdateLog() + "\n\n" +
                        "**申请人**:" + operateUserName + "\n\n" +
                        "**Message**:" + title;
                JSONObject actionCardJson = new JSONObject();
                actionCardJson.set("title", title);
                actionCardJson.set("text", content);
                actionCardJson.set("btnOrientation", "0");
                actionCardJson.set("singleTitle", "点击关闭");
                actionCardJson.set("singleURL", projectEnv + "/devops-middle.html?type=2&versionId=" + dosProjectVersion.getId());

                msgJson.set("msgtype", "actionCard");
                msgJson.set("actionCard", actionCardJson);
            } else if (ProjectVersionPhaseEnum.COMPLETED == msgType) {
                //web页面点击发布完成
                String title = "发布完成";
                String operateUserName = "";
                List<DOSProjectVersionOperateLog> acceptLogList = logMap.get(DevOpsConstant.ProjectVersionOperateActionType.PUBLISH_FINISH);
                if (CollectionUtil.isNotEmpty(acceptLogList)) {
                    DOSProjectVersionOperateLog firstAcceptLog = acceptLogList.get(0);
                    if (firstAcceptLog.getId() != null && StrUtil.isNotBlank(firstAcceptLog.getOperateUserName())) {
                        operateUserName = firstAcceptLog.getOperateUserName();
                    }
                }
                String content = "**项目组**:" + projectPo.getGroupName() + "\n\n" +
                        "**项目**:" + projectPo.getProjectName() + "\n\n" +
                        "**版本**:" + dosProjectVersion.getVersionCode() + "\n\n" +
                        "**更新日志**:" + dosProjectVersion.getUpdateLog() + "\n\n" +
                        "**发布人**:" + operateUserName + "\n\n" +
                        "**Message**:" + title;

                JSONObject mdJson = new JSONObject();
                mdJson.set("title", title);
                mdJson.set("text", content);
                msgJson.set("msgtype", "markdown");
                msgJson.set("markdown", mdJson);
            }
            for (DOSProjectWebhook webhook : webhooks) {
                try {
                    String webhookUrl = WebhookUtil.dealWebHook(webhook.getWebhook(), webhook.getSecret());

                    HttpRequest.post(webhookUrl).body(JSON.toJSONString(msgJson)
                            , "application/json;charset=UTF-8").execute().body();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


    }

}
